<template>
	<view class="container">
		<!-- 顶部搜索框 -->
		<view class="search-container">
			<view class="search-bar" @click="navigateToSearch">
				<text class="iconfont">&#xe61b;</text>
				<text class="placeholder">搜索商品</text>
			</view>
		</view>

		<!-- 可左右滑动的大分类 -->
		<scroll-view scroll-x class="first-cate-container" @scrolltolower="loadMoreFirstCate">
			<view class="first-cate-item" v-for="item in firstCateList" :key="item.id"
				:class="{active: currentFirstCateId === item.id}" @click="switchFirstCate(item)">
				<text>{{item.name}}</text>
			</view>
		</scroll-view>

		<!-- 分类和商品区域 -->
		<view class="content-container">
			<!-- 左侧小分类 -->
			<scroll-view scroll-y class="son-cate-container">
				<view class="son-cate-item" v-for="item in sonCateList" :key="item.id"
					:class="{active: currentSonCateId === item.id}" @click="switchSonCate(item)">
					<text>{{item.name}}</text>
				</view>
			</scroll-view>

			<!-- 右侧商品列表 - 替代方案：使用scroll-view实现上拉加载 -->
			<scroll-view scroll-y class="goods-container" @scrolltolower="onScrollToLower">
				<view class="goods-list">
					<view class="goods-item" v-for="goods in goodsList" :key="goods.id">
						<view class="goods-image">
							<image :src="goods.thumb" mode="aspectFill"></image>
						</view>
						<view class="goods-info">
							<view class="goods-main-info">
								<text class="goods-name">{{goods.goods_name}}</text>
								<text class="goods-description">{{goods.description || '暂无描述'}}</text>
								<text class="goods-price">{{goods.sell_price}}元/{{goods.company}}</text>
							</view>
							<view class="goods-stock">
								<text>库存: {{goods.num}}</text>
							</view>
						</view>
						<view class="add-cart-btn" @click="showSpecModal(goods)">加入购物车</view>
					</view>

					<!-- 加载中提示 -->
					<view class="loading-more" v-if="isLoadingMore">
						<uni-loading type="circle" size="16"></uni-loading>
						<text>加载中...</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 规格选择弹窗组件 -->
		<spec-modal v-if="currentGoods" :goods="currentGoods" :show.sync="specModalShow"
			@confirm="handleSpecConfirm"></spec-modal>
	</view>
</template>

<script>
	import specModal from '../../components/specModal.vue';
	import api, {
		getFirstCate,
		getSonCate
	} from '../../api/request';

	export default {
		components: {
			specModal
		},
		data() {
			return {
				firstCateList: [], // 大分类列表
				sonCateList: [], // 小分类列表
				goodsList: [], // 商品列表
				currentFirstCateId: 0, // 当前选中的大分类ID
				currentSonCateId: 0, // 当前选中的小分类ID
				currentGoods: null, // 当前选中的商品
				specModalShow: false, // 规格弹窗显示状态
				page: 1, // 商品列表页码
				hasMore: true, // 是否有更多商品
				isAllSelected: false, // 全选状态
				isLoadingMore: false, // 是否正在加载更多商品
				cateIdFromUrl: 0, // 从URL参数获取的分类ID
			};
		},
		onLoad() {
			// 从本地存储获取分类ID
			this.cateIdFromUrl = uni.getStorageSync('categoryId') || 0;
			// 加载大分类
			this.loadFirstCate();
		},

		onShow() {
			// 每次显示页面时检查是否有新的分类ID
			const newCateId = uni.getStorageSync('categoryId') || 0;
			if (newCateId && newCateId !== this.currentFirstCateId) {
				this.cateIdFromUrl = newCateId;
				// 如果已经加载过分类列表，则直接切换
				if (this.firstCateList.length > 0) {
					const targetCate = this.firstCateList.find(item => item.id == this.cateIdFromUrl);
					if (targetCate) {
						this.switchFirstCate(targetCate);
					}
				}
			}
		},
		// 上拉加载更多 - 修复版
		// onReachBottom() {
		// 	if (this.hasMore) {
		// 		this.loadGoodsList();
		// 	} else {
		// 		uni.showToast({
		// 			title: '没有更多商品了',
		// 			icon: 'none'
		// 		});
		// 	}
		// },

		// 替代方案：使用scroll-view的scrolltolower事件
		// 在template中的goods-container添加scroll-view并绑定事件
		// <scroll-view scroll-y class="goods-container" @scrolltolower="onScrollToLower">

		methods: {
			// 跳转到搜索页面
			navigateToSearch() {
				uni.navigateTo({
					url: '/pages/index/search'
				})
			},
			onScrollToLower() {
				if (this.hasMore) {
					this.loadGoodsList();
				} else {
					uni.showToast({
						title: '没有更多商品了',
						icon: 'none'
					});
				}
			},
			// 加载大分类
			loadFirstCate() {
				const params = {
					id: 1,
					name: '干货调料'
				};

				getFirstCate(params)
					.then(res => {
						if (res.data && res.data.length) {
							this.firstCateList = res.data;
							// 检查是否有从URL传入的分类ID
							if (this.cateIdFromUrl) {
								// 查找对应的分类
								const targetCate = res.data.find(item => item.id == this.cateIdFromUrl);
								if (targetCate) {
									this.switchFirstCate(targetCate);
								} else if (res.data.length > 0) {
									// 默认选中第一个大分类
									this.switchFirstCate(res.data[0]);
								}
							} else if (res.data.length > 0) {
								// 默认选中第一个大分类
								this.switchFirstCate(res.data[0]);
							}
						}
					})
					.catch(err => {
						console.error('获取大分类失败:', err);
					});
			},

			// 切换大分类
			switchFirstCate(item) {
				this.currentFirstCateId = item.id;
				this.currentSonCateId = 0;
				this.sonCateList = [];
				this.goodsList = [];
				this.page = 1;
				this.hasMore = true;

				// 清除本地存储中的分类ID
				uni.removeStorageSync('categoryId');

				// 加载小分类
				this.loadSonCate(item.id);
			},

			// 加载小分类
			loadSonCate(parentId) {
				const params = {
					parent_id: parentId
				};

				getSonCate(params)
					.then(res => {
						if (res.data && res.data.length) {
							this.sonCateList = res.data;
							// 默认选中第一个小分类
							if (res.data.length > 0) {
								this.switchSonCate(res.data[0]);
							}
						}
					})
					.catch(err => {
						console.error('获取小分类失败:', err);
					});
			},

			// 切换小分类
			switchSonCate(item) {
				this.currentSonCateId = item.id;
				this.goodsList = [];
				this.page = 1;
				this.hasMore = true;

				// 加载商品列表
				this.loadGoodsList();
			},

			// 加载商品列表
			loadGoodsList() {
				if (!this.hasMore || this.isLoadingMore) return;

				this.isLoadingMore = true;

				const params = {
					page: this.page,
					cate_id: this.currentSonCateId
				};

				api.getGoodsList(params)
					.then(res => {
						this.isLoadingMore = false;
						if (res.data && res.data.rows && res.data.rows.length) {
							if (this.page === 1) {
								this.goodsList = res.data.rows.map(item => ({
									...item,
									selected: false
								}));
							} else {
								this.goodsList = [...this.goodsList, ...res.data.rows.map(item => ({
									...item,
									selected: false
								}))];
							}

							// 判断是否还有更多商品
							this.hasMore = res.data.rows.length === 10; // 假设每页10条
							this.page++;
						} else {
							this.hasMore = false;
						}
					})
					.catch(err => {
						this.isLoadingMore = false;
						console.error('获取商品列表失败:', err);
					});
			},

			// 显示规格选择弹窗
			showSpecModal(goods) {
				this.currentGoods = goods;
				this.specModalShow = true;
			},

			// 处理规格确认
			handleSpecConfirm(data) {
				// 这里处理从规格弹窗返回的数据
				// 通常包含商品ID、数量和选中的规格
				const params = {
					goods_id: data.goods.id,
					num: data.num,
					item: data.spec.id
				};

				// 调用添加购物车接口
				api.addCart(params)
					.then(res => {
						uni.showToast({
							title: '添加购物车成功',
							icon: 'success'
						});
					})
					.catch(err => {
						uni.showToast({
							title: err.msg || '添加购物车失败',
							icon: 'none'
						});
					});
			},

			// 加载更多大分类（如果有分页）
			loadMoreFirstCate() {
				// 这里实现大分类的上拉加载更多逻辑
				// 根据实际接口情况进行调整
			},

			// 全选/取消全选
			toggleAllSelect() {
				this.isAllSelected = !this.isAllSelected;
				this.goodsList.forEach(item => {
					item.selected = this.isAllSelected;
				});
			},

			// 切换单个商品选择
			toggleSelect(index) {
				this.goodsList[index].selected = !this.goodsList[index].selected;
				this.isAllSelected = this.goodsList.every(item => item.selected);
			}
		}
	};
</script>

<style scoped lang="less">
	/* 搜索框样式 */
	.search-container {
		padding: 10px;
		background-color: #fff;
	}

	.search-bar {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 40px;
		background-color: #f5f5f5;
		border-radius: 20px;
		padding: 0 15px;
	}

	.search-bar .iconfont {
		color: #999;
		margin-right: 5px;
	}

	.search-bar .placeholder {
		color: #999;
		font-size: 14px;
	}

	/* 大分类样式 */
	.first-cate-container {
		height: 50px;
		background-color: #fff;
		white-space: nowrap;
		padding: 0 10px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
	}

	.first-cate-item {
		display: inline-block;
		height: 50px;
		line-height: 50px;
		padding: 0 15px;
		font-size: 14px;
		color: #333;
	}

	.first-cate-item.active {
		color: #e63946;
		border-bottom: 2px solid #e63946;
	}

	/* 内容区域样式 */
	.content-container {
		display: flex;
		height: calc(100vh - 100px);
	}

	/* 左侧小分类样式 */
	.son-cate-container {
		width: 25%;
		height: 100%;
		background-color: #f5f5f5;
	}

	.son-cate-item {
		padding: 15px;
		font-size: 14px;
		color: #333;
		border-bottom: 1px solid #eee;
	}

	.son-cate-item.active {
		background-color: #fff;
		color: #e63946;
	}

	/* 右侧商品列表样式 */
	.goods-container {
		width: 75%;
		height: 100%;
		padding: 0 20rpx 20rpx 20rpx;
		overflow-y: auto;
		background-color: #f9f9f9;
	}

	.goods-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.goods-item {
		display: flex;
		// width: 100%;
		background-color: #fff;
		border-radius: 10rpx;
		overflow: hidden;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		position: relative;
	}

	.goods-image {
		width: 180rpx;
		height: 180rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.goods-image image {
		width: 100%;
		height: 100%;
		display: block;
		border-radius: 8rpx;
	}

	.goods-info {
		flex: 1;
		display: flex;
		justify-content: space-between;
	}

	.goods-main-info {
		flex: 1;
	}

	.goods-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}

	.goods-description {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 12rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}

	.goods-price {
		font-size: 28rpx;
		color: #e63946;
		font-weight: bold;
	}

	.goods-stock {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
		padding-left: 20rpx;

		text {
			font-size: 24rpx;
			color: #999;
		}
	}

	.add-cart-btn {
		position: absolute;
		bottom: 20rpx;
		right: 20rpx;
		background-color: #FE0000;
		color: #fff;
		font-size: 24rpx;
		padding: 0 20rpx;
		height: 50rpx;
		line-height: 50rpx;
		border-radius: 25rpx;
		z-index: 10;
	}

	/* 加载中提示样式 */
	.loading-more {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		font-size: 24rpx;
		color: #999;
	}
</style>